#!/usr/bin/env python

#Copyright (C) 2008 Luis Felipe Millani (lf.millani@gmail.com)

#This file is part of MagicLyrics.

#MagicLyrics is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#MagicLyrics is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with MagicLyrics.  If not, see <http://www.gnu.org/licenses/>.



# this is a modified version of cookielib_example.py ((C) Michael Foord, 2004), which can be downloaded from
# http://www.voidspace.org.uk/python/recipebook.shtml#cookielib

from sys import stderr

import os.path
import urllib2
import urllib
import socket
socket.setdefaulttimeout(3)


cj = None
ClientCookie = None
cookielib = None

# Let's see if cookielib is available
try:
	import cookielib
except ImportError:
	# If importing cookielib fails
	# let's try ClientCookie
	try:
		import ClientCookie
	except ImportError:
		# ClientCookie isn't available either
		urlopen = urllib2.urlopen
		Request = urllib2.Request
	else:
		# imported ClientCookie
		urlopen = ClientCookie.urlopen
		Request = ClientCookie.Request
		cj = ClientCookie.LWPCookieJar()

else:
	# importing cookielib worked
	urlopen = urllib2.urlopen
	Request = urllib2.Request
	cj = cookielib.LWPCookieJar()
	# This is a subclass of FileCookieJar
	# that has useful load and save methods



if cj is not None:
# we successfully imported
# one of the two cookie handling modules

	# Now we need to get our Cookie Jar
	# installed in the opener;
	# for fetching URLs
	if cookielib is not None:
		# if we use cookielib
		# then we get the HTTPCookieProcessor
		# and install the opener in urllib2
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
		urllib2.install_opener(opener)

	else:
		# if we use ClientCookie
		# then we get the HTTPCookieProcessor
		# and install the opener in ClientCookie
		opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(cj))
		ClientCookie.install_opener(opener)



def download(url,data=None):
	"""
	download given url; supports cookies
	
	url    url to be downloaded
	data   POST stuff
	e.g. download('http://somesite.invalid/login',{'username':'root','password':'toor'})
	"""
	if not data==None:
		data=urllib.urlencode(data)
	
	headers =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
	# fake a user agent, some websites (like google) don't like automated exploration
	
	try:
		req = Request(url, data, headers)
		# create a request object
		
		handle = urlopen(req)
		# and open it to return a handle on the url
	
	except IOError, e:
		print >> stderr,'We failed to open "%s".' % url
		if hasattr(e, 'code'):
			print >> stderr,'We failed with error code - %s.\n' % e.code
		elif hasattr(e, 'reason'):
			print >> stderr,"The error object has the following 'reason' attribute :"
			print >> stderr,e.reason
			print >> stderr,"This usually means the server doesn't exist,",
			print >> stderr,"is down, or we don't have an internet connection.\n"
		raise
	except URLError, e:
		print >> stderr,'URLError: %s\n'%e
		raise
	
	read=handle.read()
	handle.close()
	return read